import re
from enum import Enum
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import sys


class ParagraphType(Enum):
    FirstLevel = 1  # 一级标题
    SecondLevel = 2  # 二级标题
    ThirdLevel = 3  # 三级标题
    FourthLevel = 4  # 四级标题
    FifthLevel = 5  # 五级标题
    SixthLevel = 6  # 六级标题
    RawTextLevel = 100  # 纯文本，没有标题


font_size_mapping = {
    "初号": 42,
    "小初": 36,
    "一号": 28,
    "小一": 24,
    "二号": 22,
    "小二": 18,
    "三号": 16,
    "小三": 15,
    "四号": 14,
    "小四": 12,
    "五号": 10.5,
    "小五": 9,
    "六号": 7.5,
    "小六": 6.5,
    "七号": 5.5,
    "八号": 5
}


def get_quan_from_num(num):
    if num == 1:
        return "①"
    if num == 2:
        return "②"
    if num == 3:
        return "③"
    if num == 4:
        return "④"
    if num == 5:
        return "⑤"
    if num == 6:
        return "⑥"
    if num == 7:
        return "⑦"
    if num == 8:
        return "⑧"
    if num == 9:
        return "⑨"
    if num == 10:
        return "⑩"

    try:
        # 你的代码逻辑
        raise Exception("遇到了无法处理的数字")
    except Exception as e:
        print(f"捕获到异常: {e}")
        sys.exit(1)  # 退出程序


def num_to_chinese(num):
    """
    将0-99之间的整数转换成中文数字。

    :param num: 整数，0-99之间的数字
    :return: 字符串，中文数字表示
    """
    if not isinstance(num, int) or not (0 <= num <= 99):
        raise ValueError("输入必须是0到99之间的整数")

    units = ["", "十", "百", "千", "万"]  # 这里只用到“十”，其他单位作为扩展参考
    digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
    teens = ["十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九"]

    if num < 10:
        return digits[num]
    elif num < 20:
        return teens[num - 10]
    else:
        ten_place = num // 10  # 十位
        one_place = num % 10  # 个位
        if one_place == 0:
            return digits[ten_place] + units[1]
        else:
            return digits[ten_place] + units[1] + digits[one_place]


def get_paragraph_type_info(text):

    pattern6 = r'^\b\d+\.\d+.\d+.\d+.\d+.\d+\b'
    matches = re.findall(pattern6, text)
    if matches:
        return ParagraphType.SixthLevel, matches[0]
    pattern5 = r'^\b\d+\.\d+.\d+.\d+.\d+\b'
    matches = re.findall(pattern5, text)
    if matches:
        return ParagraphType.FifthLevel, matches[0]
    pattern4 = r'^\b\d+\.\d+.\d+.\d+\b'
    matches = re.findall(pattern4, text)
    if matches:
        return ParagraphType.FourthLevel, matches[0]
    pattern3 = r'^\b\d+\.\d+.\d+\b'
    matches = re.findall(pattern3, text)
    if matches:
        return ParagraphType.ThirdLevel, matches[0]
    pattern2 = r'^\b\d+\.\d+\b'
    matches = re.findall(pattern2, text)
    if matches:
        return ParagraphType.SecondLevel, matches[0]
    pattern1 = r'^\b\d+\b'
    matches = re.findall(pattern1, text)
    if matches:
        return ParagraphType.FirstLevel, matches[0]

    return ParagraphType.RawTextLevel, ""


def find_text_with_graph(line_text):
    return line_text[line_text.find(" "):]


def get_index_text_for_paragraph(level, index_string):
    last_num = int(index_string.split('.')[-1])
    if level == ParagraphType.ThirdLevel:
        return f"（{num_to_chinese(last_num)}）"
    if level == ParagraphType.FourthLevel:
        return f"{last_num}."

    if level == ParagraphType.FifthLevel:
        return f"（{last_num}）"
    if level == ParagraphType.SixthLevel:
        return get_quan_from_num(last_num)

    try:
        # 你的代码逻辑
        raise Exception("遇到了无法处理的索引")
    except Exception as e:
        print(f"捕获到异常: {e}")
        sys.exit(1)  # 退出程序


def set_common_paragraph_format(paragraph_param):
    para_format = paragraph_param.paragraph_format
    para_format.line_spacing = Pt(29)
    para_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
    para_format.first_line_indent = Pt(24)  # 首行缩进
    para_format.space_after = Pt(0)  # 段后间距
    para_format.space_before = Pt(0)


def set_common_run_format(run_param, is_tiao):
    run_param.font.size = Pt(font_size_mapping["三号"])  # 字体大小
    run_param.font.name = "FangSong"
    # run_param._element.rPr.rFonts.set(qn('w:eastAsia'), 'FangSong')
    if not run_param._element.rPr:
        rPr = run_param._element.add_rPr()
    else:
        rPr = run_param._element.rPr
    # 如果 rFonts 不存在，则创建它
    if not rPr.rFonts:
        rFonts = OxmlElement('w:rFonts')
        rPr.append(rFonts)
    else:
        rFonts = rPr.rFonts

    # 设置中文字体
    rFonts.set(qn('w:eastAsia'), 'FangSong')
    if is_tiao:
        run_param.bold = True


if __name__ == '__main__':
    doc_name = "福建省福能海韵发电有限公司-筹融资"
    print("--------------开始将Excel转Word--------------")
    doc = Document()
    with open('./ban_gong_yong_pin.txt', 'r', encoding='utf-8') as text_file:
        last_paragraph_info = ParagraphType.RawTextLevel, ""
        # 二级标题，当前所在的是多少条
        second_num = 1

        for line in text_file:
            print(f"process:{line}")
            line = line.replace('\n', '')
            if line.isspace() or not line:
                print("发现了空格")
                continue
            paragraph_type_info = get_paragraph_type_info(line)
            last_paragraph_info = paragraph_type_info
            paragraph_type = paragraph_type_info[0]
            paragraph_num = paragraph_type_info[1]

            if paragraph_type == ParagraphType.FirstLevel:
                # print(f"找到了一级标题:{line}")
                first_level_num = paragraph_num
                first_level_chinese = f"第{num_to_chinese(int(first_level_num))}章  {find_text_with_graph(line)}"
                paragraph = doc.add_paragraph()
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                para_format = paragraph.paragraph_format
                para_format.line_spacing = Pt(29)
                para_format.space_before = Pt(0)
                para_format.space_after = Pt(0)
                run = paragraph.add_run(first_level_chinese)
                run.font.size = Pt(font_size_mapping["三号"])  # 字体大小
                run.font.name = '黑体'  # 字体类型
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
                continue

            if paragraph_type == ParagraphType.SecondLevel:
                paragraph = doc.add_paragraph()
                set_common_paragraph_format(paragraph)

                chinese_tiao = num_to_chinese(second_num)
                second_level_chinese = f"第{chinese_tiao}条  "

                tiao_run = paragraph.add_run(second_level_chinese)
                set_common_run_format(tiao_run, True)

                run = paragraph.add_run(find_text_with_graph(line))
                set_common_run_format(run, False)
                second_num += 1
                # print(f"找到了二级标题:{line}")
                continue

            if paragraph_type == ParagraphType.RawTextLevel:
                paragraph = doc.add_paragraph()
                set_common_paragraph_format(paragraph)

                run = paragraph.add_run(line)
                set_common_run_format(run, False)
                # print(f'找到了纯文本内容:{line}')
                continue

            # 处理其它段落
            paragraph = doc.add_paragraph()
            set_common_paragraph_format(paragraph)
            index_text = get_index_text_for_paragraph(paragraph_type, paragraph_num)

            tiao_run = paragraph.add_run(index_text)
            set_common_run_format(tiao_run, False)

            run = paragraph.add_run(find_text_with_graph(line))
            set_common_run_format(run, False)

    doc.save("福建省福能海韵发电有限公司-办公用品.docx")
    print("--------------开始将Excel转Word--------------")
